package com.itheima.pinda.mapstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author llhuang10
 * @date 2021/10/3 22:32
 */
@Component
public class MyList2StringMapper {


    /**
     * 猜测List初始数据类型
     */
    public String list2Str(List<List<Map>> list) {
        StringBuilder builder = new StringBuilder();

        list.forEach(mapList -> {
            mapList.forEach(map -> {
                for (Object key : map.keySet()) {
                    builder.append("(")
                            .append(key)
                            .append(",")
                            .append(map.get(key))
                            .append(")")
                            .append(" ");
                }
                builder.substring(0, builder.toString().length() - 1);
            });
            builder.append("|");
        });
        return builder
                .substring(0, builder.toString().length() - 1)
                .trim();
    }


    /**
     * str 在DB中格式  (0,1) (0,2) (2,3) |(0,1) (0,2) (2,3)
     *
     * @param entityStr
     * @return
     */
    public List<List<Map>> strList2(String entityStr) {
        String[] split = entityStr.split("\\|");

        List<List<Map>> result = new ArrayList<>();

        Arrays.stream(split).filter(StringUtils::isNotBlank)
                .forEach(
                        listStr -> {
                            List<Map> mapArrayList = new ArrayList<>();
                            String[] str = listStr.split(" ");
                            for (String s : str) {
                                // todo 一个 s -> 类型为         (1,2) (12,32) (23,34)
                                String trim = s.trim();
                                String[] split1 = trim.substring(1, trim.length() - 1).split(",");
                                Map hashMap = new HashMap();
                                hashMap.put(split1[0], split1[1]);
                                mapArrayList.add(hashMap);
                            }
                            result.add(mapArrayList);
                        }
                );
        return result;
    }
}
